<template>
  <div class="homework-analysis">
    <h3 class="scoreStateTitle">作业分析</h3>
    <!-- 2.3.1 作业质量 -->
    <div class="homework-quality">
      <h3 class="header-with-select anchor-offset" id="Homework-quality">作业质量</h3>
      <el-card v-loading="loading">
        <div class="quality-overview">
          <ul>
            <li>
              满分
              <span v-if="homeworkqualitylist && homeworkqualitylist.length > 0">
                <i>{{ homeworkqualitylist[0].fullScore }}</i>/分
              </span>
            </li>
            <li>
              人数
              <span>
                <i>{{ homeworkqualitylist[0].submitCount }}</i>/人
              </span>
            </li>
            <li>
              难度
              <span>
                <i>{{ homeworkqualitylist[0].difficulty }}</i>
              </span>
            </li>
            <li>
              信度
              <span>
                <i>{{ homeworkqualitylist && homeworkqualitylist.length > 0 ? homeworkqualitylist[0].difficulty : 0
                  }}</i>
              </span>
            </li>
            <li>
              区分度
              <span>
                <i>{{ homeworkqualitylist && homeworkqualitylist.length > 0 ? homeworkqualitylist[0].discrimination : 0
                  }}</i>
              </span>
            </li>
          </ul>
        </div>
        <el-table :data="homeworkqualitylistable || []" border stripe
          :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
          tooltip-effect="dark" style="width: 100%">
          <el-table-column prop="indicator" label="指标" align="center" width="120" />
          <el-table-column prop="paperEvaluation" label="整卷评价" align="center" />
          <el-table-column label="试题" align="center">
            <!-- prop="questionEvaluation" -->
            <template #default="scope">
              <span v-html="scope.row.questionEvaluation"
                style="text-align: left;display: inline-block;padding:5px 10px;"></span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
	  <div id="Test-score-rate"></div>
		  <h3 class="header-with-select" style="margin-top:24px;">试题得分率</h3>
		  <el-card>
		    <el-table
			v-if="questionscorerateapilist.length > 0 && questionscorerateapilist[0].questionList"
		      :data="questionscorerateapilist"
		      border
		      stripe
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%"
		    >
				<el-table-column prop="name"  label="全体/班级" align="center" ></el-table-column>
				<el-table-column
					v-for="(scored, index) in questionscorerateapilist[0].questionList"
					:key="index"
					:label="`${scored.questionNum}`"
					>
					<template #default="{ row }">
					{{ row.questionList[index].scoreRate }}%
					</template>
				</el-table-column>
		    </el-table>
		  </el-card>
	  </div>
	  <div id="Test-knowledge-rate">
		  <h3 class="header-with-select" style="margin-top:24px;">知识点得分率</h3>
		  <el-card v-if="knowledgescoreratelist&&knowledgescoreratelist.length>0">
		    <el-table
		      :data="knowledgescoreratelist"
		      border
		      stripe
			  :height="knowledgescoreratelist.length > 5 ? '504px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%"
		    >
				<el-table-column prop="knowledge" label="" align="center" width="150"></el-table-column>
				<el-table-column
					width="100"
					v-for="(question, index) in knowledgescoreratelist[0].knowledgeScoreInfos || []"
					:key="question.name"
					:label="question.name+'得分率'">
					<template slot-scope="scope">
						{{ scope.row.knowledgeScoreInfos[index].scoreRate }}%
					</template>
				</el-table-column>
		    </el-table>
		  </el-card>
	  </div>
	  <div id="Small-question-analysis">
		  <h3 class="header-with-select" style="margin-top:24px;">小题分析（全体线/班级线）</h3>
		  <el-card v-loading="loading">
		    <div ref="questionAnalysisChart" style="width: 100%; height: 400px" v-if="smallquestionlist.length>0"></div>
			<div v-else style="line-height: 60px;width:100%;color: #909399;text-align: center;font-size:14px;">暂无数据</div>
		  </el-card>
	  </div>
	  <div id="Objective-Question-Answering">
		  <h3 class="header-with-select" style="margin-top:24px;">客观题作答分布</h3>
		  <el-card v-loading="loading">
		    <el-table :data="objectiveAnswerData" border stripe
			:height="objectiveAnswerData.length > 5 ? '504px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%">
		      <el-table-column prop="questionNum" label="试题" align="center" />
		      <el-table-column prop="answer" label="答案" align="center" />
		      <el-table-column prop="score" label="分值" align="center" />
		      <el-table-column prop="avgScore" label="平均分" align="center" />
		      <el-table-column prop="scoreRate" label="得分率(%)" align="center" />
		      <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
		      <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
		      <el-table-column label="学生作答" align="center" width="400">
		  			    <template slot-scope="scope">
		  					<ul class="studentanswer">
		  						<li v-for="option in scope.row.newstudentAnswer" :class="{'hover': isHighestPercentage(scope.row, option)}">{{option}}</li>
		  					</ul>
		  			    </template>
		  		  </el-table-column>
		    </el-table>
		  </el-card>
	  </div>
	  <div id="subjective-Question-Answering">
		  <h3 class="header-with-select" style="margin-top:24px;">主观题得分分布（分数划分见考情名次解释-分数划分）</h3>
		  <el-card v-loading="loading">
		    <el-table :data="subjectiveAnswerData" border stripe
			:height="subjectiveAnswerData.length > 5 ? '504px' : undefined"
		      :header-cell-style="{ background: '#E8F0FA', color: '#2A303B',fontWeight:'500' }"
		      class="custom-table"
		      tooltip-effect="dark"
		      style="width: 100%">
		      <el-table-column prop="questionNum" label="试题" align="center" />
		      <el-table-column prop="answer" label="答案" align="center" />
		      <el-table-column prop="score" label="分值" align="center" />
		      <el-table-column prop="avgScore" label="平均分" align="center" />
		      <el-table-column prop="scoreRate" label="得分率(%)" align="center" />
		      <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
		      <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
		      <el-table-column label="学生作答" align="center" width="500">
		  			  <template slot-scope="scope">
		  				<ul class="studentanswer">
		  					<li v-for="(option,cindex) in scope.row.newstudentAnswer" :class="{'hover': isHighestPercentage1(scope.row, option)}">{{option}}</li>
		  				</ul>
		  			  </template>
		  		  </el-table-column>
		    </el-table>
		  </el-card>
	  </div>
    </div>

  </div>
</template>

<script>
import {
  homeworkqualityApi,
  questionscorerateapi,
  knowledgescorerateapi,
  smallquestionapi,
  objectiveanswerapi,
  subjectiveanswerapi
} from '@/api/grade'
import * as echarts from 'echarts'

export default {
  name: 'HomeworkAnalysis',
  components: {
  },
  props: {
    examId: {
      type: [String, Number],
      required: true
    },
    classIds: {
      type: [String, Number],
      required: true
    },
    classIds1: {
      type: [Array],
      required: true
    },
  },
  data () {
    return {
      //   qualityData: {
      //     fullScore: 0,
      //     submitCount: 0,
      //     difficulty: 0,
      //     discrimination: 0,
      //     evaluations: []
      //   },
      matrixData: [],
      scoreRatesData: [],
      questionAnalysisData: [],
      objectiveAnswerData: [],
      subjectiveAnswerData: [],
      loading: false,
      questionAnalysisChart: null,
      hasLoaded: false,
      loadingPromise: null,
      knowledgeRatesData: [],

      homeworkqualitylist: [],
      homeworkqualitylistable: [],
      questionscorerateapilist: [],
      knowledgescoreratelist: [],
      smallquestionlist: []
    }
  },
  methods: {
    //作业质量
    async homerowkqualitytab () {
      this.homeworkqualitylist = []
      this.homeworkqualitylistable = []
      try {
        const res = await homeworkqualityApi(
          Number(this.examId),
          String(this.classIds)
        )
        if (res.code === 200) {
          console.info('scorerangeTable', res)
          this.homeworkqualitylist = res.data
          this.homeworkqualitylistable = res.data[0].evaluations
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    // 试题得分率
    async questionscorerateapitab () {
      this.questionscorerateapilist = []
      try {
        const res = await questionscorerateapi(
          Number(this.examId),
          String(this.classIds)
        )
        if (res.code === 200) {
          this.questionscorerateapilist = res.data
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    //知识点得分率
    async knowledgescoreratetab () {
      this.knowledgescoreratelist = []
      try {
        const res = await knowledgescorerateapi(
          Number(this.examId),
          String(this.classIds)
        )
        if (res.code === 200) {
          this.knowledgescoreratelist = res.data
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    //小题分
    async smallquestiontab () {
      this.smallquestionlist = []
      try {
        const res = await smallquestionapi(
          Number(this.examId),
          String(this.classIds)
        )
        if (res.code === 200) {
          this.smallquestionlist = res.data
          this.$nextTick(() => {
            // 先销毁旧图表
            if (this.questionAnalysisChart) {
              this.questionAnalysisChart.dispose();
              this.questionAnalysisChart = null;
            }
            // 重新初始化图表
            this.initQuestionAnalysisChart(res.data);
          });
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    //客观题
    async objectivetab () {
      this.objectiveAnswerData = []
      try {
        const res = await objectiveanswerapi(
          Number(this.examId),
          String(this.classIds)
        )
        if (res.code === 200) {
          this.objectiveAnswerData = res.data.map(item => ({
            ...item,
            newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
          }));
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },
    //主观题
    async subjectivetab () {
      this.subjectiveAnswerData = []
      try {
        const res = await subjectiveanswerapi(
          Number(this.examId),
          String(this.classIds)
        )
        if (res.code === 200) {
          this.subjectiveAnswerData = res.data.map(item => ({
            ...item,
            newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
          }));
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },

    getDifficultyClass (difficulty) {
      switch (difficulty) {
        case '简单':
          return 'green';
        case '较易':
          return 'zs';
        case '一般':
          return 'blue';
        case '困难':
          return 'yellow';
        default:
          return 'red';
      }
    },
    handleResize () {
      if (this.questionAnalysisChart) {
        this.questionAnalysisChart.resize();
      }
    },
    initQuestionAnalysisChart (data) {
      console.log('Initializing chart with data:', data);

      // 检查 DOM 元素是否存在
      if (!this.$refs.questionAnalysisChart) {
        console.warn('Chart ref not found');
        return;
      }

      // 初始化 ECharts 实例
      if (!this.questionAnalysisChart) {
        this.questionAnalysisChart = echarts.init(this.$refs.questionAnalysisChart);
      }

      // 防御性代码：确保 data 存在且结构正确
      if (!data || data.length === 0) {
        console.warn('No data available');
        return;
      }

      // 生成 xAxis 数据（使用第一个数据项的questionList作为基准）
      const xAxisData = data[0].questionList.map(item => `${item.questionNum}`);

      // 定义系列数据
      const series = data.map(group => ({
        name: group.name,
        type: 'line',
        data: group.questionList.map(item => parseFloat(item.scoreRate)),
        smooth: false,
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          opacity: 0.5,
        },
        showSymbol: true
      }));

      const colors = ['#295CFF', '#FF6B6B', '#6BCB77'];
      series.forEach((item, index) => {
        if (!item) return; // 跳过空数据

        // 循环取颜色，避免越界
        const color = colors[index % colors.length];

        // 设置线条颜色
        item.lineStyle = {
          ...item.lineStyle, // 保留原有配置
          color: color,
        };

        // 设置区域渐变颜色
        item.areaStyle = {
          ...item.areaStyle, // 保留原有配置
          color: new echarts.graphic.LinearGradient(
            0, 1, 0, 0,
            [
              { offset: 1, color: color },
              { offset: 0.2, color: 'rgba(255, 255, 255, 0.8)' }, // 建议用 rgba
              { offset: 0, color: 'rgba(255, 255, 255, 0)' }
            ]
          ),
        };
      });

      // ECharts 配置项
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let tooltipContent = `${params[0].name}<br/>`;
            params.forEach((item) => {
              tooltipContent += `${item.marker} ${item.seriesName}: ${item.value}%<br/>`;
            });
            return tooltipContent;
          },
        },
        legend: {
          data: data.map(item => item.name),
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
        },
        yAxis: {
          type: 'value',
          name: '得分率(%)',
          min: 0,
          max: 100,
          interval: 20,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#cccccc',
            },
          },
        },
        series: series,
      };

      // 设置图表配置
      this.questionAnalysisChart.setOption(option);
    },
    getDifficultyType (difficulty) {
      switch (difficulty) {
        case '容易': return 'success';
        case '中等': return 'warning';
        case '困难': return 'danger';
        default: return 'info';
      }
    },
    async loadMatrixData () {
      try {
        const res = await getQuestionMatrix(this.examId, this.classId);
        if (res.code === 200) {
          this.matrixData = res.data;
        }
      } catch (error) {
        console.error('加载双向细目表失败:', error);
      }
    },
    isHighestPercentage (row, option) {
      const options = row.newstudentAnswer;
      const correctAnswer = row.answer;

      // 提取每个选项的百分比
      const percentages = options.map(opt => {
        const match = opt.match(/\((\d+\.\d+)%\)/);
        return match ? parseFloat(match[1]) : 0;
      });

      // 找出与正确答案不同的选项
      const incorrectOptions = options.filter(opt => !opt.includes(correctAnswer));

      // 找出占比最高的选项
      const maxPercentage = Math.max(...percentages);

      // 判断当前选项是否是占比最高的且不是正确答案
      return option.includes(correctAnswer) ? false : percentages[options.indexOf(option)] === maxPercentage;
    },
    isHighestPercentage1 (row, option) {
      const options = row.newstudentAnswer;

      // 提取每个选项的百分比
      const percentages = options.map(opt => {
        const match = opt.match(/\((\d+\.\d+)%\)/);
        return match ? parseFloat(match[1]) : 0;
      });


      // 找出占比最高的选项
      const maxPercentage = Math.max(...percentages);

      // 判断当前选项是否是占比最高的且不是正确答案
      return percentages[options.indexOf(option)] === maxPercentage;
    }
  },
  mounted () {
    this.homerowkqualitytab()
    this.questionscorerateapitab()
    this.knowledgescoreratetab()
    this.smallquestiontab()
    this.objectivetab()
    this.subjectivetab()
    // console.log('HomeworkAnalysis mounted');
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.handleResize);
    if (this.questionAnalysisChart) {
      this.questionAnalysisChart.dispose();
    }
  },
  created () {
    console.log('HomeworkAnalysis created with props:', {
      examId: this.examId,
      classId: this.classId
    });
  },
  watch: {
    classIds1: {
      handler (newVal, oldVal) {
        if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;

        console.log('classIds 变化:', oldVal, '→', newVal);
        this.classIds = newVal.join(',');

        // 按顺序调用所有数据更新方法
        Promise.all([
          this.homerowkqualitytab(),
          this.questionscorerateapitab(),
          this.knowledgescoreratetab(),
          this.smallquestiontab(), // 包含图表更新
          this.objectivetab(),
          this.subjectivetab()
        ]).catch(error => {
          console.error('数据加载错误:', error);
        });
      },
      immediate: true,
      deep: true
    },
    examId: {
      handler (newVal, oldVal) {
        console.info(newVal + '-----' + oldVal)
        if (JSON.stringify(newVal) === JSON.stringify(oldVal)) return;
        this.homerowkqualitytab(),
          this.questionscorerateapitab(),
          this.knowledgescoreratetab(),
          this.smallquestiontab(), // 包含图表更新
          this.objectivetab(),
          this.subjectivetab()
      },
      immediate: true,  // 立即触发一次
      deep: true       // 字符串不需要深度监听
    }
  }
}
</script>

<style scoped>
.homework-quality {
  background: #FFFFFF;
  box-shadow: 0 4px 16px 0 #5572921a;
  border-radius: 10px;
  padding: 24px;
}

.quality-overview {
  margin-bottom: 20px;
}

.quality-overview ul {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
}

.quality-overview ul li {
  box-sizing: border-box;
  height: 78px;
  border-radius: 10px;
  padding: 0 14px;
  flex: 1;
  font-size: 16px;
  padding-top: 10px;
}

.quality-overview ul li span {
  display: block;
  font-size: 16px;
  font-style: normal;
  color: #B3B8C2;
  padding-top: 2px;
}

.quality-overview ul li span i {
  font-style: normal;
  font-size: 24px;
  font-weight: bold;
}

.quality-overview ul li:nth-child(1) {
  background: rgb(247, 249, 255);
  border: solid 1px rgb(231, 236, 255)
}

.quality-overview ul li:nth-child(1) span i,
.quality-overview ul li:nth-child(2) span i {
  color: #295CFF
}

.quality-overview ul li:nth-child(2) {
  background: rgb(247, 249, 255);
  border: solid 1px rgb(231, 236, 255)
}

.quality-overview ul li:nth-child(3) {
  background: rgba(236, 85, 90, 0.04);
  border: solid 1px rgba(236, 85, 90, 0.1)
}

.quality-overview ul li:nth-child(4) {
  background: rgb(253, 251, 247);
  border: solid 1px rgb(249, 243, 231)
}

.quality-overview ul li:nth-child(5) {
  background: rgb(247, 251, 248);
  border: solid 1px rgb(230, 242, 233)
}

.quality-overview ul li:nth-child(3) span i,
.quality-overview ul li:nth-child(4) span i {
  color: #2A303B
}

.header-with-select {
  font-size: 16px;
  color: #2A303B;
  margin-bottom: 14px;
}

.pending-data {
  color: #909399;
  font-style: italic;
}

.question-matrix {
  margin-top: 20px;
}

.scoreStateTitle {
  font-size: 18px;
  color: #295CFF;
  line-height: 45px;
  font-weight: normal;
  position: relative;
  padding-left: 25px;
  font-weight: bold;
}

.scoreStateTitle:after {
  content: '';
  width: 14px;
  height: 14px;
  opacity: 0.5;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 0;
  top: 15px;
}

.scoreStateTitle::before {
  content: '';
  width: 8px;
  height: 8px;
  opacity: 0.2;
  background: #295CFF;
  border-radius: 14px;
  position: absolute;
  left: 10px;
  top: 23px;
}

.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 1);
  border-radius: 10px;
  border-right: none;
  border-bottom: none;
  margin-top: 0;
}

/* 自定义表格内部元素的样式 */
.custom-table>>>.el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal
}

.custom-table>>>.el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-bottom: none;
  border-right: solid 1px rgba(216, 228, 240, 1);
}

.el-table .warning-row {
  background: #ffffff;
}

.el-table .success-row {
  background: #D8E4F0;
}

.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover,
.el-cascader__dropdown,
.el-color-picker__panel,
.el-message-box,
.el-notification {
  box-shadow: none;
}

.homework-quality>>>.el-card__body,
.homework-quality>>>.el-main {
  padding: 0 !important;
}

.homework-quality>>>.el-card {
  border: none;
}

.studentanswer {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 4px 0;
}

.studentanswer li {
  background: rgb(242, 244, 251);
  border: solid 1px rgb(216, 225, 255);
  height: 30px;
  border-radius: 10px;
  font-size: 14px;
  color: #295CFF;
  padding: 0 14px;
  line-height: 30px;
  margin: 4px 7px;
}

.studentanswer li.hover {
  background: rgb(250, 243, 245);
  border: solid 1px rgb(247, 212, 215);
  color: #EC555A;
}

.tabbox {
  display: inline-block;
  width: 60px;
  height: 22px;
  border-radius: 10px;
}

.green {
  background: rgb(225, 248, 233);
  border: 1px solid rgb(18, 107, 255);
  color: #29CE67;
}

.zs {
  background: rgb(242, 236, 255);
  border: 1px solid rgb(224, 209, 255);
  color: #A777FF;
}

.blue {
  background: rgb(229, 238, 255);
  border: 1px solid rgb(167, 196, 254);
  color: #4985FF
}

.yellow {
  background: rgb(255, 243, 236);
  border: 1px solid rgb(255, 211, 181);
  color: #FFAB77;
}

.red {
  background: rgb(255, 236, 236);
  border: 1px solid rgb(255, 189, 189);
  color: #FF7777;
}
.anchor-offset {
  scroll-margin-top: 50px;
}
</style>
